// characters模板
class answers {
    // 传入mongoose对象
    constructor(mongoose) {
        this.mongoose = mongoose
        this.Schema = mongoose.Schema
        // CharactersInfo
        this.answersInfo = new this.Schema({
            id: Number,
            questionId: Number,
            contents: String,
            school: String,
            praiseNumber: Number,
            name: String,
            class: String,
            commentNumber: Number,
            date: Date,
            userId: Number,
            priasePeople: Array,
        })
        this.modal = this.mongoose.model('Answer', this.answersInfo)
    }
    // 插入答案
    async insertAnswer(obj) {
        var answer = new this.modal({
            id: Math.random() * 100000000000000000,              // 什么内容的(比如某张cos图)的id
            questionId: obj.questionId,
            contents: obj.contents,
            school: obj.school,
            praiseNumber: 0,
            name: obj.name,
            class: obj.class,
            commentNumber: 0,
            date: new Date(),
            userId: obj.userId,
            priasePeople: []
        })
        return answer.save((err, data) => {
            if (err) {
                console.log(err)
                return false
            }
            else {
                return true
            }
        })
    }
    // @paras1 查询条件 动漫名字
    // @paras2 查询结果过滤器
    // 返回查询结果
    async getAnswers(body) {

        return this.modal.find({ questionId: body.questionId }).sort({ id: 1 }).skip(10 * body.page).limit(10)
    }
    // @paras1 删除的id
    delAnswer(id) {
        // findAndModify强调原子性 也就是获取然后增加 这类很好 自然速度不如update快
        return this.modal.deleteOne({ id: id }, (err, data) => {
            if (err) { console.log(err) }
            else { return null }
        })
    }
    // 评论点赞 在该评论的priasePeople中加入点赞id
    // @paras1 点赞评论的id
    // @paras2 点赞者的id
    priase(id, priaseId) {
        return this.modal.updateOne({ id: id, priasePeople: { $ne: priaseId } }, { $push: { priasePeople: priaseId }, $inc: { priaseNumber: 1 } }, (err, data) => {
            if (err) { console.log(err) }
            else {
                return null
            }
        })
    }
    // 取消点赞
    cancelPriase(id, priaseId) {
        return this.modal.updateOne({ id: id }, { $pull: { priasePeople: priaseId }, $inc: { priaseNumber: -1 } }, (err, data) => {
            if (err) { console.log(err) }
            else { return null }
        })
    }
}

module.exports = answers